﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Collections;
using BusinessTier;

public partial class TutorInputReview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            WeekDropDown.Enabled = true;
        }
    }

    //set to update teammember text boxes with names
    //protected void groupnamedropdown()
    //{
    //  
    //}

    //set weekdropdown box to update mark and reviews?
    //protected void weekdropdown_click(object sender, EventArgs e)
    //{
    //
    //}

    protected void GroupNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Remove "Select a group..." option after initial change
        if (IsPostBack)
        {
            GroupNameDropDown.Items[0].Enabled = false;
        }

        string teamname = GroupNameDropDown.Text;
        BusinessTier.TutorReview data = new BusinessTier.TutorReview(teamname);
        DataTable students = data.groupDetails();

        setMarks(data);

        // counter initialised for foreach loop
        int counter = 1;

        // ContentPlaceHolder object is used by master pages to store 
        // user specified content, here we initialise an emtpy instance
        ContentPlaceHolder contentPlaceHolder;

        // We now look for the main body of our page using FindControl() 
        // (which returns an aspx control) on the master object (i.e. the page in question). 
        // This is type casted as a ContentPlaceHolder object then stored in the 
        // pre-initialised object above
        contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("pagebody");

        // Text box objects are initialised to use as references for the username 
        // and user ID text boxes on page
        TextBox userNameTextBox;
        TextBox userIDTextBox;
        DropDownList userGradeList;

        DataTable marks = setMarks(data);

        foreach (Control control in contentPlaceHolder.Controls)
        {
            TextBox textboxes = new TextBox();

            if (control.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                textboxes = (TextBox)control;
                textboxes.Text = "";
            }
        }

        // loop runs through the rows (i.e. the records) stored in DataTable object 'students'
        foreach (DataRow row in students.Rows)
        {
            if (row["user_id"].ToString() != GroupNameDropDown.Text.ToString())
            {
                // This part only runs for the other group members i.e.: not the current student
                // i.e.: only if the student number of this record doesnt match the student 
                // number of the currently authenticated student
                // ---
                // How it works: 
                // With each loop there is a new text box stored in the objects initialise above
                // (i.e. userNameTextBox and userIDTextBox), these are found by using FindControl()
                // on the ContentPlaceHolder object then type casted as a text box.
                // The data in columns [user_name] and [user_id] of this record is then set to the text
                // of their respective text boxes. These text boxes are then disabled so they can't
                // be changed by the user. 
                // Finally the counter is incremented - you may notice that as part of the argument
                // in the the FindControl() calls that the counter is appended. This ensures that
                // each loop looks for the next text box e.g.: Loop 1 = StudentNameTextBox2, 
                // Loop 2 = StudentNameTextBox3 etc. You may also notice that we start at text box 2,
                // this is because the first text box belongs to the current user.
                userNameTextBox = (TextBox)contentPlaceHolder.FindControl("StudentNameTextBox" + counter.ToString());
                userIDTextBox = (TextBox)contentPlaceHolder.FindControl("StudentNumberTextBox" + counter.ToString());

                userGradeList = (DropDownList)contentPlaceHolder.FindControl("GradeList" + counter.ToString());
                //foreach (

                userNameTextBox.Text = row["user_name"].ToString();
                //SubmitStatusLabel.Text = marks.Columns[0].ToString();
                //SubmitStatusLabel.Text += marks.Columns[1].ToString();
                foreach (DataRow resultRow in marks.Rows)
                {
                    SubmitStatusLabel.Text = resultRow["user_id"].ToString();
                    if (resultRow["user_id"].ToString().Trim() == row["user_id"].ToString().Trim())
                    {
                        userGradeList.SelectedValue = resultRow["mark"].ToString();
                        SubmitStudentReviewButton.Text = "Update";
                        SubmitStudentReviewButton.Click += UpdateStudentReviewButton_Click;
                    }
                }
                userIDTextBox.Text = row["user_id"].ToString();
                userNameTextBox.Enabled = false;
                userIDTextBox.Enabled = false;
                counter++;
            }
            else
            {
                // When the record's user ID matches that of the current user the same actions
                // performed above is done but for the first text box. This is because the first
                // text box is allocated for self reflection.
                userNameTextBox = (TextBox)contentPlaceHolder.FindControl("StudentNameTextBox1");
                userIDTextBox = (TextBox)contentPlaceHolder.FindControl("StudentNumberTextBox1");
                userNameTextBox.Text = row["user_name"].ToString();
                userIDTextBox.Text = row["user_id"].ToString();
                userNameTextBox.Enabled = false;
                userIDTextBox.Enabled = false;
            }
        }

        //Update the values of each team members grade and comments using the specified week

    }

    protected void SubmitStudentReviewButton_Click(object sender, EventArgs e)
    {
        List<List<string>> results = submitResults();

        string dataConnection = "Data Source=localhost;Initial Catalog=INB201;Integrated Security=True";

        SqlConnection connect = new SqlConnection(dataConnection);
        connect.Open();

        //insert week user_id mark comment

        SqlCommand dataCommand = new SqlCommand();
        dataCommand.Connection = connect;

        //string week = weekdropdown.DataValueField;
        string week;
        string user_name;
        string user_id;
        string mark;
        string comment;

        //insert values into tutorresults table
        foreach (List<string> result in results)
        {
            week = WeekDropDown.Text;
            user_name = result[0];
            user_id = result[1];
            mark = result[2];
            comment = result[3];

            dataCommand.CommandText = "INSERT INTO tutorresults(week, user_name, user_id, mark, comment)";
            dataCommand.CommandText += "VALUES (" + week + ",'" + user_name + "','" + user_id + "'," + mark + ",'" + comment + "')";
            SqlDataReader datareader = dataCommand.ExecuteReader();
            datareader.Close();
        }

        connect.Close();

    }

    private List<List<string>> submitResults()
    {
        List<List<string>> results = new List<List<string>>();
        string[] toAdd = new string[4];
        List<string> record = new List<string>();
        ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("pagebody");
        int counter = 1;
        foreach (Control control in contentPlaceHolder.Controls)
        {
            string studentEntries = "";
            //List<TextBox> textboxes = new List<TextBox>();
            //List<DropDownList> dropdown = new List<DropDownList>();

            TextBox textboxes = new TextBox();
            DropDownList dropdown = new DropDownList();

            string studentNumberTextBox = "StudentNumberTextBox" + counter.ToString();
            string studentNameTextBox = "StudentNameTextBox" + counter.ToString();
            string gradeDropdownList = "GradeList" + counter.ToString();
            string commentsTextBox = "CommentsTextBox" + counter.ToString();

            if (control.GetType().ToString() == "System.Web.UI.WebControls.TextBox" &&
                control.ID.ToString() == studentNumberTextBox)
            {
                textboxes = (TextBox)control;
                studentEntries = textboxes.Text;
            }

            if (control.GetType().ToString() == "System.Web.UI.WebControls.TextBox" &&
                control.ID.ToString() == studentNameTextBox)
            {
                textboxes = (TextBox)control;
                studentEntries = textboxes.Text;
            }

            if (control.GetType().ToString() == "System.Web.UI.WebControls.DropDownList" &&
                control.ID.ToString() == gradeDropdownList)
            {
                dropdown = (DropDownList)control;
                studentEntries = dropdown.Text;
            }

            if (control.GetType().ToString() == "System.Web.UI.WebControls.TextBox" &&
                control.ID.ToString() == commentsTextBox)
            {
                textboxes = (TextBox)control;
                studentEntries = textboxes.Text;
            }

            if (studentEntries != null && studentEntries != "")
            {

                record.Add(studentEntries);
                toAdd[record.Count - 1] = studentEntries;
                if (record.Count == 4)
                {

                    List<string> list = toAdd.ToList();
                    results.Add(list);
                    record.Clear();
                    counter++;
                }
            }

            foreach (List<string> result in results)
            {
                SubmitStatusLabel.Text += result[0] + ", " + result[1] + ", " + result[2] + ", " + result[3] + ", ";
            }

        }
        return results;
    }

    protected void UpdateStudentReviewButton_Click(object sender, EventArgs e)
    {
        List<List<string>> results = submitResults();
        string dataConnection = "Data Source=localhost;Initial Catalog=INB201;Integrated Security=True";

        SqlConnection connect = new SqlConnection(dataConnection);
        connect.Open();

        //insert week user_id mark comment

        SqlCommand dataCommand = new SqlCommand();
        dataCommand.Connection = connect;

        //string week = weekdropdown.DataValueField;
        string week;
        string user_name;
        string user_id;
        string mark;
        string comment;

        //insert values into tutorresults table
        foreach (List<string> result in results)
        {
            week = WeekDropDown.Text;
            user_name = result[0];
            user_id = result[1];
            mark = result[2];
            comment = result[3];

            dataCommand.CommandText = "INSERT INTO tutorresults(week, user_name, user_id, mark, comment)";
            dataCommand.CommandText += "VALUES (" + week + ",'" + user_name + "','" + user_id + "'," + mark + ",'" + comment + "')";
            SqlDataReader datareader = dataCommand.ExecuteReader();
            datareader.Close();
        }

        connect.Close();

    }


    protected void WeekDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {

        string teamname = GroupNameDropDown.Text;
        BusinessTier.TutorReview data = new BusinessTier.TutorReview(teamname);
        setMarks(data);
    }

    private DataTable setMarks(TutorReview data)
    {
        DataTable results = data.groupMarks(WeekDropDown.Text);
        DataTable students = data.groupDetails();
        DataTable studentResults = new DataTable();

        //Duplicate the results dataTable format for use in studentResults
        studentResults = results.Clone();

        //Loop through each row in the results dataTable
        foreach (DataRow result in results.Rows)
        {
            foreach (DataRow student in students.Rows)
            {
                if (result["user_id"].ToString().Trim() == student["user_id"].ToString().Trim())
                {
                    studentResults.ImportRow(result);
                }
            }
        }


        return studentResults;
    }

}



